package com.zwx.string.leetcode_4;

/**
 * 验证回文字符串
 * 输入: "A man, a plan, a canal: Panama"
 * 输出: true
 * 输入: "race a car"
 * 输出: false
 *
 * @author 文希
 * @create 2019-07-01 23:51
 */
public class IsPalindrome {

    /**
     * 思路：
     * 首先将字符串全部小写处理，并记录有效字符串（去除符号空格等），
     * 再首尾两端向中间移动，一次比较
     */
    private static boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        s = s.toLowerCase();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if ((s.charAt(i) >= 'a' && s.charAt(i) <= 'z') ||
                    (s.charAt(i) >= '0' && s.charAt(i) <= '9')) {
                result.append(s.charAt(i));
            }
        }
        if (result.length() == 0) {
            return true;
        }
        int st = 0;
        int end = result.length() - 1;
        while (st < end) {
            if (result.charAt(st) != result.charAt(end)) {
                return false;
            } else {
                st++;
                end--;
            }
        }
        return true;
    }

    public static void main(String[] args) {
//        String s = "A man, a plan, a canal: Panama";
        String s1 = "race a car";
//        boolean palindrome = isPalindrome(s);
//        System.out.println("palindrome = " + palindrome);
        boolean b = isPalindrome(s1);
        System.out.println("b = " + b);
    }
}
